import os, sys, time

# Get all script
scriptdata = sys.stdin.read()

# Get unix timestamp for the job id
unixtime = int(time.time());
# Printing the job id needs to be done in the parent
# before daemonisation
print(str(unixtime));
sys.stdout.flush();

pid = os.fork();
if (pid != 0):
   # parent complete
   os._exit(0);

# Make child head of an independent process group
os.setsid();
pid = os.fork();
if (pid != 0):
   # child complete
   os._exit(0);

# Close all open files
maximum_fd_number = os.sysconf("SC_OPEN_MAX");
for fd in range(maximum_fd_number):
   try:
      os.close(fd);
   except OSError:
      pass;

# Make a standard error log file
se = open("queued_%s_e.log" % str(unixtime), 'w', 0);
# Make a standard output log file
so = open("queued_%s_o.log" % str(unixtime), 'w', 0);
# Also set env variable to pretend to be a queue proper
os.environ['PBS_JOBID'] = str(unixtime);

# redirect
os.dup2(se.fileno(), sys.stderr.fileno());
os.dup2(so.fileno(), sys.stdout.fileno());

# Execute our script as the queue would
if (sys.argv[1] == '-V'):
   os.execv('/bin/sh', ['sh', '-c', '%s' % scriptdata]);
